<template>
  <div class="global-header">
    <div class="header-content">
      <!-- 左侧Logo和标题 -->
      <div class="header-left">
        <div class="logo-section">
          <img src="/logo.svg" alt="Logo" class="logo" />
          <span class="site-title">AI Market</span>
        </div>
        
        <!-- 导航菜单 -->
        <a-menu
          v-model:selectedKeys="selectedKeys"
          mode="horizontal"
          class="header-menu"
          :items="menuItems"
          @click="handleMenuClick"
        />
      </div>
      
      <!-- 右侧用户区域 -->
      <div class="header-right">
        <div v-if="!isLoggedIn">
          <a-button type="primary" @click="handleLogin">
            登录
          </a-button>
        </div>
        <div v-else class="user-info">
          <a-dropdown>
            <a-button type="text" class="user-button">
              <UserOutlined />
              {{ userInfo?.userName || userInfo?.userAccount || '用户' }}
              <DownOutlined />
            </a-button>
            <template #overlay>
              <a-menu @click="handleUserMenuClick">
                <a-menu-item key="profile">
                  <UserOutlined />
                  个人资料
                </a-menu-item>
                <a-menu-item key="my-apps">
                  <AppstoreOutlined />
                  我的应用
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item key="logout">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { UserOutlined, DownOutlined, AppstoreOutlined, LogoutOutlined } from '@ant-design/icons-vue'
import type { MenuProps } from 'ant-design-vue'
import { getUserInfo, logout } from '@/api/auth'
import type { User, UserVO } from '@/types/api'
import { eventBus, EVENT_TYPES } from '@/utils/eventBus'

const router = useRouter()
const route = useRoute()

// 当前选中的菜单项
const selectedKeys = ref<string[]>(['home'])

// 用户信息
const userInfo = ref<UserVO | null>(null)

// 是否管理员
const isAdmin = computed(() => userInfo.value?.userRole === 'admin')

// 登录状态
const isLoggedIn = computed(() => {
  const tokenName = localStorage.getItem('tokenName')
  const tokenValue = localStorage.getItem('tokenValue')
  return !!(tokenName && tokenValue && userInfo.value)
})

// 菜单配置
const menuItems = computed<MenuProps['items']>(() => [
  {
    key: 'home',
    label: '首页',
    title: '首页'
  },
  {
    key: 'apps',
    label: '应用市场',
    title: '应用市场'
  },
  {
    key: 'create',
    label: '创建应用',
    title: '创建应用'
  },
  {
    key: 'library',
    label: '个人图书馆',
    title: '个人图书馆'
  },
  {
    key: 'docs',
    label: 'API文档',
    title: 'API文档'
  },
  ...(isAdmin.value ? [{ key: 'admin-violations', label: '违规统计', title: '违规统计' }] : [])
])

// 处理菜单点击
const handleMenuClick: MenuProps['onClick'] = (e) => {
  console.log('菜单点击:', e.key)
  // 这里可以根据菜单项进行路由跳转
  switch (e.key) {
    case 'home':
      router.push('/')
      break
    case 'apps':
      router.push('/app-market')
      break
    case 'create':
      router.push('/create-app')
      break
    case 'library':
      router.push('/personal-library')
      break
    case 'docs':
      router.push('/api-docs')
      break
    case 'admin-violations':
      router.push('/admin/violations')
      break
  }
}

// 处理登录按钮点击
const handleLogin = () => {
  console.log('登录按钮点击')
  router.push('/login')
}

// 处理用户菜单点击
const handleUserMenuClick = async (e: any) => {
  switch (e.key) {
    case 'profile':
      // 跳转到个人资料页面
      router.push('/profile')
      break
    case 'my-apps':
      router.push('/my-apps')
      break
    case 'logout':
      await handleLogout()
      break
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await logout()
    // 清除Sa-Token相关数据
    localStorage.removeItem('tokenName')
    localStorage.removeItem('tokenValue')
    localStorage.removeItem('userId')
    localStorage.removeItem('userInfo')
    userInfo.value = null
    message.success('退出登录成功')
    router.push('/')
  } catch (error) {
    console.error('退出登录失败:', error)
    // 即使接口失败也清除本地数据
    localStorage.removeItem('tokenName')
    localStorage.removeItem('tokenValue')
    localStorage.removeItem('userId')
    localStorage.removeItem('userInfo')
    userInfo.value = null
    router.push('/')
  }
}

// 初始化用户信息
const initUserInfo = async () => {
  const tokenName = localStorage.getItem('tokenName')
  const tokenValue = localStorage.getItem('tokenValue')
  
  if (tokenName && tokenValue) {
    // 首先尝试从localStorage获取缓存的用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        userInfo.value = JSON.parse(userInfoStr)
      } catch (error) {
        console.error('解析用户信息失败:', error)
        localStorage.removeItem('userInfo')
      }
    }
    
    // 然后尝试从服务器获取最新的用户信息
    try {
      const response = await getUserInfo()
      if (response.code === 0) {
        userInfo.value = response.data
        localStorage.setItem('userInfo', JSON.stringify(response.data))
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取失败，清除token信息
      localStorage.removeItem('tokenName')
      localStorage.removeItem('tokenValue')
      localStorage.removeItem('userId')
      localStorage.removeItem('userInfo')
      userInfo.value = null
    }
  }
}

// 页面初始化
onMounted(() => {
  initUserInfo()
  
  // 监听用户登录事件
  eventBus.on(EVENT_TYPES.USER_LOGIN, () => {
    console.log('收到用户登录事件，刷新用户信息')
    initUserInfo()
  })
})

// 监听路由变化，当从登录页面跳转时刷新用户信息
watch(() => route.path, (newPath, oldPath) => {
  if (oldPath === '/login' && newPath !== '/login') {
    // 从登录页面跳转到其他页面时，延迟刷新用户信息
    setTimeout(() => {
      initUserInfo()
    }, 100)
  }
})

// 监听localStorage变化（当其他标签页登录时）
window.addEventListener('storage', (e) => {
  if (e.key === 'tokenName' || e.key === 'tokenValue') {
    initUserInfo()
  }
})

// 定期检查token状态（每30秒检查一次）
setInterval(() => {
  const tokenName = localStorage.getItem('tokenName')
  const tokenValue = localStorage.getItem('tokenValue')
  if (tokenName && tokenValue && !userInfo.value) {
    initUserInfo()
  }
}, 30000)
</script>

<style scoped>
.global-header {
  width: 100%;
  height: 64px;
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.header-left {
  display: flex;
  align-items: center;
  flex: 1;
}

.logo-section {
  display: flex;
  align-items: center;
  margin-right: 40px;
}

.logo {
  height: 32px;
  width: 32px;
  margin-right: 12px;
}

.site-title {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
  white-space: nowrap;
}

.header-menu {
  flex: 1;
  border-bottom: none;
  line-height: 64px;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .global-header {
    height: 56px;
  }
  
  .header-content {
    padding: 0 16px;
  }
  
  .logo-section {
    margin-right: 20px;
  }
  
  .site-title {
    font-size: 18px;
  }
  
  .header-menu {
    line-height: 56px;
  }
  
  /* 在小屏幕上隐藏部分菜单项 */
  .header-menu :deep(.ant-menu-item:nth-child(n+3)) {
    display: none;
  }
}

@media (max-width: 480px) {
  .header-content {
    padding: 0 12px;
  }
  
  .logo-section {
    margin-right: 12px;
  }
  
  .site-title {
    font-size: 16px;
  }
  
  .logo {
    height: 28px;
    width: 28px;
    margin-right: 8px;
  }
  
  /* 在更小屏幕上只显示首页菜单 */
  .header-menu :deep(.ant-menu-item:nth-child(n+2)) {
    display: none;
  }
}

/* 覆盖Ant Design的默认样式 */
.header-menu :deep(.ant-menu-item) {
  border-bottom: 2px solid transparent;
}

.header-menu :deep(.ant-menu-item-selected) {
  border-bottom-color: #1890ff;
}

.header-menu :deep(.ant-menu-item:hover) {
  border-bottom-color: #40a9ff;
}
</style>